import React, { useState, useEffect } from 'react'
import { View, Image, Button, Picker } from '@tarojs/components'
import { AtIcon, AtInput, AtList, AtListItem } from "taro-ui"
import Taro,{useDidShow}  from '@tarojs/taro'
import api from '../../http/api'


import './index.less'
import "taro-ui/dist/style/components/input.scss";
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/button.scss";


export default (props: any) => {
  // 手机号
  const [tel, setTel] = useState('')
  // 学校
  const [school, setSchool] = useState('')
  // 学校列表
  const [schoolList, setSchoolList] = useState([])
  // 学校列表带ID
  const [schoolListId, setSchoolListId] = useState([])
  useDidShow(() => {
    // console.log()
    login()
    getSchoolEnter()
  })

  // 提交
  const onSubmit = (e: any) => {
    console.log(props.tid)
    const url = props.tid.split('url=')[1].split('&')[0]
    if(!tel.length){
      Taro.showToast({
        title: '请填点击获取手机号码',
        icon: 'none'
      })
    }else if(!getSchoolId(school)){
      Taro.showToast({
        title: '请选择学校',
        icon: 'none'
      })
    }else{
      Taro.showModal({
        title: '提示',
        content: '登录前往U你校园',
        complete: function (res:any) {
          if(res.confirm){
            wx.getUserProfile({
              desc: '正在获取',
              success: function(res) {
                if(res.userInfo){
                  // 获取到用户信息验证码正确
                  const {nickName,avatarUrl} = res.userInfo
                  api.loginV2({
                    tel,
                    nickName,
                    avatarUrl,
                    uSchoolId:getSchoolId(school)
                  }).then((res:any)=>{
                    Taro.setStorage({
                      key:'info',
                      data:JSON.stringify(res.data)
                    })
                    Taro.reLaunch({
                      url:fomatUrl(url)
                    })
                  })
                }else{
                  Taro.showToast({
                    title: '请先授权',
                    icon: 'none'
                  })
                }
              }
            })
          }
        }
      })
      
    }
  }
  const fomatUrl = (url:any)=>{
    let urlR = url
    if(url.indexOf('ZN')>-1){
      urlR = url.replace('ZN','?')
    }
    return urlR
  }
  // 获取手机号
  const getTel = (e) => {
    const { iv, encryptedData } = e.detail
    if (iv) {
      api.wxgetTel({
        iv, encryptedData,
        sessionKey: JSON.parse(Taro.getStorageSync('wxinfo')).session_key
      }).then((res: any) => {
        const { data } = res
        const { phoneNumber } = data
        setTel(phoneNumber)
      })
    } else {
      Taro.showToast({
        title: '请允许手机访问',
        icon: 'none',
      })
    }

  }
  // 微信登录
  const login = ()=>{
    Taro.login({
      success: function (res) {
        if (res.code) { 
          api.wxlogin({
            js_code: res.code
          }).then((res: any) => {
            Taro.setStorage({
              key: 'wxinfo',
              data: JSON.stringify(res.data)
            })
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  }
  // 获取入驻学校列表
  const getSchoolEnter = ()=>{
    api.getSchoolEnter().then((res:any)=>{
      const {data} = res
      setSchoolListId(data)
      const arr = []
      data.map((item:any)=>{
        arr.push(item.name)
      })
      setSchoolList(arr)
    })
  }
  // 学校改变
  const schoolChange = (e)=>{
    const index = parseInt(e.target.value)
    setSchool(schoolList[index]) 
  }
  // 根据学校名称获取入驻学校编号
  const getSchoolId = (name:any)=>{
    let id = null
    schoolListId.map(item=>{
      if(item.name===name){
        id = item.id
      }
    })
    return id
  }

  return (
    <View className='login'>
      <View className='intro'>
        {/* <View className='i1'>产品定位服务于大学生群体</View> */}
        <View className='i1'>请点击获取手机号并选择学校</View>
        <View className='i2'>进入U你校园学习生活、校园资讯综合平台</View>
      </View>
      <Image className='bg' src={IMGSRC + 'bgLogin.png'}></Image>
      <View className='loginForm'>
        <AtIcon size={20} value='iphone-x' className="ico"></AtIcon>
        <AtIcon size={20} value='search' className="ico2 ico"></AtIcon>
        <Button  open-type='getPhoneNumber' onGetPhoneNumber={getTel} className='getTel' type='primary' >获取手机号</Button>
        <AtInput
          placeholderStyle={'color:#666;font-size:14px'}
          className='input'
          name='tel'
          type='number'
          placeholder='请点击获取手机号'
          editable={false}
          value={tel}
          onChange={() => { }}
        > </AtInput>
        <Picker mode='selector' range={schoolList} onChange={schoolChange}>
          <AtInput
            placeholderStyle={'color:#666;font-size:14px'}
            className='input'
            name='school'
            placeholder='请选择学校'
            value={school}
            onChange={() => { }}
            editable={false}
          > </AtInput>
        </Picker>
        <Button onClick={onSubmit}  className='submit'  type='primary' >登录</Button>
      </View>
    </View>
  )
}
